#include <CompressorDocumentStorages.hpp>


#include <errno.h>
#include <MemoryDocumentInfoStorage.hpp>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <FSDumper.hpp>
#include <Util.hpp>
#include <FileDocumentStorage.hpp>
namespace FTSS {

void CompressorDocumentStorage::compress(CHAR_P pathToDataFiles, MemoryDocumentInfoStorage * memDocStorage){
	fprintf(stdout, "Compressor start working with path = %s \n" , pathToDataFiles);
	bool openingMemStorage = (memDocStorage == NULL);
	fprintf(stderr, "pathToDataFiles=%s\n", pathToDataFiles);
	fprintf(stderr, "openingMemStorage=%s\n", openingMemStorage ? "true" :"false" );
	// open old info_storage
	INT_32 iFileHandle;
	MemoryDocumentInfoStorage *oDocInfoStorage_Current;
 	if (openingMemStorage){
		oDocInfoStorage_Current = new MemoryDocumentInfoStorage();
	        iFileHandle = open(DirFilePath(pathToDataFiles, "DocumentsDB.ftss").c_str(), O_RDONLY, 0644);
        	if (iFileHandle != -1){
	        	FSDumper oDumper(iFileHandle);
		        if (oDocInfoStorage_Current->Restore(&oDumper) == -1){
		        	fprintf(stderr, "Cannot restore index `%s'.\n =>  can't COMPRESS", pathToDataFiles);
				return;
			}
			close(iFileHandle);
		}else {
			fprintf(stderr, "Cannot open index file.\n");
			return;
		}
	} else {
		oDocInfoStorage_Current = memDocStorage;
	}

	fprintf(stdout, "Document storage..."); fflush(stdout);
	FileDocumentStorage oDocumentStorage(DirFilePath(pathToDataFiles, "DocStorIndex.ftss").c_str(), DirFilePath(pathToDataFiles, "DocStorData.ftss").c_str(), C_READ_MODE);
	fprintf(stdout, "OK\n");


	fprintf(stdout, "Document storage..."); fflush(stdout);
 	FileDocumentStorage oDocumentStorage_compressed(DirFilePath(pathToDataFiles, "DocStorIndex_compressed.ftss").c_str(), DirFilePath(pathToDataFiles, "DocStorData_compressed.ftss").c_str(), C_READ_WRITE_MODE);
	fprintf(stdout, "OK\n");
	
	oDocInfoStorage_Current->compressInfoStorage(oDocumentStorage, oDocumentStorage_compressed);

	// create new file info storage
	if (openingMemStorage){
		iFileHandle = open(DirFilePath(pathToDataFiles, "DocumentsDB_Compressed.ftss").c_str(), O_CREAT | O_WRONLY, 0644);
		if (iFileHandle != -1){
			FSDumper oDumper(iFileHandle);
			if (oDocInfoStorage_Current->Dump(&oDumper) != 0) { 
				fprintf(stdout, "ERROR: Cannot dump document info!\n"); 
			}
	 		close(iFileHandle);
		} else {
			fprintf(stdout, "ERROR: Cannot open document info file for writing!\n"); 
		}
		close(iFileHandle);
		delete(oDocInfoStorage_Current);
		fprintf(stderr,"HERE");
	}
}

} //namespace FTSS 


